package server

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	log "github.com/sirupsen/logrus"
)

type ServerPlugin struct {
	engine *gin.Engine
	upgrader websocket.Upgrader
	conHub *connectionHub
	mHub *messageHub

	globalCh chan struct{}
}

func NewServerPlugin(globalCh chan struct{}) *ServerPlugin {
	s := ServerPlugin{
		engine: customEngine(),
		upgrader: websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool {
				return true
			},
		},
		globalCh: globalCh,
	}

	s.conHub = NewConnHub()
	s.mHub = NewMessageHub()
	return &s
}

func (s *ServerPlugin) Start(globalCh chan struct{}) error {
	go s.doStart()
	return nil 
}

func (s * ServerPlugin) doStart() {
	s.engine.GET("/kill", func (c *gin.Context)  {
		s.globalCh <- struct{}{}
		c.String(200, "ok")
	})

	s.engine.GET("/chat", func(ctx *gin.Context) {
		request := ctx.Request
		respWriter := ctx.Writer

		client := ctx.Param("clientId")

		conn, err := s.upgrader.Upgrade(respWriter, request, nil)
		if err != nil {
			log.Error(err.Error())
			ctx.String(500, err.Error())
			return 
		}

		connection := NewConn(client, s.conHub, s.mHub, conn)
		connection.Start()
	})

	server := http.Server{
		Addr: ":8080",
		Handler: s.engine,
	}
	server.ListenAndServe()
}

func (s *ServerPlugin) Stop() {
	s.conHub.Stop()
	s.mHub.Stop()
}

func customEngine() *gin.Engine {
	return gin.Default()
}

